<?php

namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;
use GatewayClient\Gateway;

class CustomerSessionInfo extends Model
{

    public static function findBySkey($skey)
    {
        return self::query()->where('skey', $skey)->first();
    }

    public static function storeUserInfo($userinfo, $sessionKey)
    {
        $union_id = $userinfo['unionId'];
        $open_id = $userinfo['openId'];

        // 更新
        $nick_name = $userinfo['nickName'];
        $gender = $userinfo['gender'];
        $language = $userinfo['language'];
        $country = $userinfo['country'];
        $province = $userinfo['province'];
        $city = $userinfo['city'];
        $avatar_url = $userinfo['avatarUrl'];
        $watermark = json_encode($userinfo['watermark']);

        $platform = env('PLATFORM_ID');

        $query = self::query();
        $query->where('platform', $platform);
        $query->where(function ($query) use ($union_id, $open_id) {
            $query->where('open_id', $open_id);
            if (!empty($union_id)) {
                $query->orWhere('union_id', $union_id);
            }
        });
        // 获取session
        $model = $query->first();
        if (!$model) {
            $model = new CustomerSessionInfo();
            $model->open_id = $open_id;
            $model->union_id = $union_id;
            $model->platform = $platform;
        }

        if (!$model->union_id && $union_id) {
            $model->union_id = $union_id;
        }

        // 有时候如果用户先访问过web，就会导致小程序的open_id写不进去，出现open_id为空的情况。所以这里要做一下处理
        if (!$model->open_id) {
            $model->open_id = $open_id;
        }
        $model->nick_name = $nick_name;
        $model->gender = $gender;
        $model->language = $language;
        $model->country = $country;
        $model->province = $province;
        $model->city = $city;
        $model->avatar_url = $avatar_url;
        $model->watermark = $watermark;
        $model->session_key = $sessionKey;

        $model->save();

        return $model;
    }

    public static function storeUserInfo2($sessionInfo)
    {

        // sessionInfo只有openid, unionid, session_key三个字段
        $union_id = $sessionInfo['unionid'] ?? null;
        $open_id = $sessionInfo['openid'];
        $sessionKey = $sessionInfo['session_key'];

//        $platform = env('PLATFORM_ID');

        // 2. 生成 3rd key (skey)
        $skey = sha1($sessionKey . mt_rand());

        //判断当前用户是否是新用户
        $isNewUser = 2;

        $query = self::query();

//        $query->where('platform', $platform);
        $query->where(function ($query) use ($union_id, $open_id) {
            $query->where('open_id', $open_id);
            if (!empty($union_id)) {
                $query->orWhere('union_id', $union_id);
            }
        });
        $query->orderBy('id', 'asc');
        // 获取session
        $model = $query->first();

        if (!$model) {
            $model = new CustomerSessionInfo();
            $model->open_id = $open_id;
            $model->union_id = $union_id;
//            $model->platform = $platform;
            $isNewUser = 1;
        }

        if (!$model->union_id && $union_id) {
            $model->union_id = $union_id;
        }

        // 有时候如果用户先访问过web，就会导致小程序的open_id写不进去，出现open_id为空的情况。所以这里要做一下处理
        if (!$model->open_id) {
            $model->open_id = $open_id;
        }
        $model->session_key = $sessionKey;
        $model->skey = $skey;

        $model->save();
        return ['model' => $model, 'is_new_user' => $isNewUser];
    }

    public function getNickName($user_id)
    {
        $data = self::query()->where('id', $user_id)->first();
        if ($data) {
            return $data->nick_name;
        }

        return '';
    }

    public function getAvatarUrl($user_id)
    {
        $data = self::query()->where('id', $user_id)->first();
        if ($data) {
            return $data->avatar_url;
        }

        return '';
    }


    // 判断一个用户是否在线
    public function isOnline()
    {
        return Gateway::isUidOnline($this->id);
    }

    public static function editNickName($user, $nickName)
    {
        $result = self::where('id', $user['id'])
            ->update([
                'nick_name' => $nickName
            ]);
        return $result;
    }

    public static function setOneGetId($array)
    {
        $orm = new CustomerSessionInfo();
        foreach ($array as $k => $v) {
            $orm->$k = $v;
        }
        $orm->save();
        return $orm->id;
    }

    public static function getOne($where)
    {
        $item = self::where($where)->first();
        return $item;
    }

    public static function createUser($userInfo)
    {
        $opendId = $userInfo['openid'];
        $nickName = $userInfo['nickname'];
        $sex = $userInfo['sex'];
        $avatar = $userInfo['headimgurl'];
        $city = $userInfo['city'];
        $customerInfo = self::where('web_open_id', $opendId)->first();
        if ($customerInfo) {
            return $customerInfo;
        } else {
            $id = self::setOneGetId([
                "web_open_id" => $opendId,
                "nick_name" => $nickName,
                "gender" => $sex,
                "avatar_url" => $avatar,
                "city" => $city,
            ]);
            if ($id) {
                $user = self::getOne(['id' => $id]);
                return $user;
            } else {
                return false;
            }
        }
    }



}
